package com.pyb.Interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @version 1.0
 * @Author 彭彦彬
 * @Date 2025/1/16 10:57
 */
public class Interceptor1 implements HandlerInterceptor {

    private static final String START_TIME = "requestStartTime";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在请求处理之前执行的逻辑
        System.out.println("Intercepted request before handling: " + request.getRequestURI());

        // 记录请求开始时间，可以用于计算响应时间
        request.setAttribute(START_TIME, System.currentTimeMillis());

        // 返回true表示继续流程；返回false会中断流程
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 在请求处理之后，但在视图渲染之前执行的逻辑
        System.out.println("Intercepted request after handling but before view rendering: " + request.getRequestURI());

        // 如果有ModelAndView对象，可以在此处修改模型数据或视图信息
        if (modelAndView != null) {
            modelAndView.addObject("interceptorMessage", "This message is added by the interceptor.");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完全处理完成后执行的逻辑，无论是否抛出了异常
        System.out.println("Intercepted request after completion: " + request.getRequestURI());

        // 检查是否有异常发生
        if (ex != null) {
            System.err.println("An exception occurred during request processing: " + ex.getMessage());
        } else {
            // 计算并打印请求处理时间
            long startTime = (Long) request.getAttribute(START_TIME);
            long endTime = System.currentTimeMillis();
            System.out.println("Request processing time: " + (endTime - startTime) + "ms");
        }
    }
}